package com.xiyi.shouxin.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.entity.user.User;
import com.xiyi.shouxin.init.CacheUtil;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull Object handler)
            throws Exception {
        if (request.getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        // 从header中获取token
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        if (token.contains("admin_")) {
            Admin admin = cacheUtil.getAdmin(token);
            if (admin != null) {
                cacheUtil.setAdminOperator(admin);
                return true;
            }
        }
        if (token.contains("user_")) {
            User user = cacheUtil.getUser(token);
            if (user != null) {
                cacheUtil.setUserOperator(user);
                return true;
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        throw  new RuntimeException(401 + ": 登录已过期");

     //   return false;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull Object handler,
            @Nullable Exception ex) throws Exception {
        cacheUtil.removeAdminOperator();
        cacheUtil.removeUserOperator();
    }

}
